import 'dart:async';

import 'package:aihu_getx_app/app/interceptors/white_list.dart';
import 'package:aihu_getx_app/app/routes/app_pages.dart';
import 'package:aihu_getx_app/utils/constants.dart';
import 'package:get/get.dart';

import 'login_intercept_chain.dart';

class LoginInterceptThreadManager {
  static LoginInterceptThreadManager? _threadManager;
  static Completer<bool>? _completer;

  LoginInterceptThreadManager._();

  static LoginInterceptThreadManager get() {
    _threadManager ??= LoginInterceptThreadManager._();
    return _threadManager!;
  }

  void checkLogin(void Function() nextRunnable) {
    if (LoginInterceptChain.isLogin()) {
      // 现已登录
      nextRunnable();
      return;
    }
    String currentRoute = Get.currentRoute;
    if (WhiteList.whiteList.contains(currentRoute)) {
      // 无需登录
      nextRunnable();
      return;
    }
    // 假如没有登录-先去登录页面
    Get.offNamed(Routes.userLogin,
        arguments: {Constants.jumpArgument: currentRoute});
    // 等候登录结束
    _completer = Completer<bool>();
    _completer?.future.then((result) {
      if (LoginInterceptChain.isLogin()) {
        // 现已登录
        nextRunnable();
        _completer = null;
      }
    });
  }

  // 设置登录结束
  void loginFinished() {
    _completer?.complete(true);
  }
}
